package idv.kikka.server.handler;

import idv.kikka.server.common.R;
import idv.kikka.server.service.factories.ChatGroupServiceFactory;
import idv.kikka.server.entity.ChatGroup;
import idv.kikka.common.message.GroupCreateRequestMessage;
import idv.kikka.common.message.GroupCreateResponseMessage;
import idv.kikka.server.service.ChatGroupService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage>{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        ChatGroupService chatGroupService= ChatGroupServiceFactory.getChatGroupService();
        //建群
        R<ChatGroup> result = chatGroupService.createGroup(groupName, members);
        if(result.getCode()!=1){
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,result.getMsg()));
        }
        else {
            //建群成功
            //给建群者发送成功消息
            ctx.writeAndFlush(new GroupCreateResponseMessage(true,groupName+"创建成功！"));
            //给被拉进的成员发送拉群消息
            List<Channel> membersChannel = chatGroupService.getMembersChannel(groupName).getData();//获取所有群组成员的channel
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true,"您已被拉入"+groupName));
            }
        }
    }
}
